import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { fetchValidation } from '@/utils';

import {
    queryPayexpList,
    queryPayexpCount,
    exportPayexp,
} from './service';

export type Effect = (
    action: AnyAction,
    effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
    namespace: string;
    state: {};
    effects: {
        fetch: Effect;
        count: Effect;
        export: Effect;
    };
    reducers: {
        save: Reducer;
        cleanCount: Reducer;
    };
}

const Model: ModelType = {
    namespace: 'logisCenterPayexpList',

    state: {
        data: {
            content: [],
            count: 0,
        },
    },

    effects: {
        * fetch({ payload }, { call, put }) {
            const { pageIndex, ...query } = payload.params;
            const response = yield call(queryPayexpList, query);
            const data = fetchValidation(response);
            if (data) {
                const { body: { list = [] } } = data;
                yield put({
                    type: 'save',
                    payload: {
                        type: 'list',
                        value: {
                            current: pageIndex,
                            search: payload.search,
                            maxId: payload.maxId,
                            minId: payload.minId,
                            list: list.map((item: any, index: number) => ({ ...item, index: index + 1 })),
                        },
                    },
                });
            }
        },
        * count({ payload }, { call, put }) {
            const { pageIndex, pageSize, ...query } = payload;
            const response = yield call(queryPayexpCount, query);
            const data = fetchValidation(response);
            if (data) {
                yield put({
                    type: 'save',
                    payload: { type: 'count', value: data.body },
                });
            }
        },
        * export({ payload }, { call, put }) {
            yield call(exportPayexp, payload);
        },
    },

    reducers: {
        save({ data }, { payload }) {
            if (payload.type === 'list') {
                const pos = data.content.findIndex((item: any) => item.current === payload.value.current);
                if (pos === -1) {
                    data.content.push(payload.value);
                } else {
                    data.content[pos] = payload.value;
                }
            } else if (payload.type === 'count') {
                data.count = payload.value;
            }
            return { data };
        },
        cleanCount({ data }) {
            data.count = 0;
            return { data };
        },
    },
};

export default Model;
